package org.dromara.comm_lhz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.comm_lhz.entity.AsAddressEntity;
import org.dromara.comm_lhz.mapper.AsAddressMapper;
import org.dromara.comm_lhz.service.AsAddressService;
import org.springdoc.core.converters.models.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (AsAddressEntity)表服务实现类
 *
 * @author makejava
 * @since 2024-08-11 21:58:39
 */
@Service("asAddressService")
public class AsAddressServiceImpl extends ServiceImpl<AsAddressMapper, AsAddressEntity> implements AsAddressService {

    @Autowired
    private AsAddressMapper asAddressMapper;

    @Override
    public Map<String, Object> getAddress(AsAddressEntity asAddressEntity) {
        // 创建查询条件
        QueryWrapper<AsAddressEntity> queryWrapper = new QueryWrapper<>();
        if (asAddressEntity.getRegion() != null && !asAddressEntity.getRegion().isEmpty()) {
            queryWrapper.like("region", asAddressEntity.getRegion());
        }
        if (asAddressEntity.getCommunity() != null && !asAddressEntity.getCommunity().isEmpty()) {
            queryWrapper.like("community", asAddressEntity.getCommunity());
        }

        // 执行查询获取所有结果
        List<AsAddressEntity> records = asAddressMapper.selectList(queryWrapper);

        // 去重的区域集合
        Set<String> uniqueRegions = records.stream()
            .map(AsAddressEntity::getRegion)
            .collect(Collectors.toSet());

        // 构建结果，将区域和对应的社区组成树形结构
        List<Map<String, Object>> result = uniqueRegions.stream()
            .map(region -> {
                Map<String, Object> map = new HashMap<>();
                map.put("region", region);
                List<AsAddressEntity> communities = records.stream()
                    .filter(record -> region.equals(record.getRegion()))
                    .collect(Collectors.toList());
                map.put("communities", communities);
                return map;
            }).collect(Collectors.toList());

        // 构造返回的结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", result);
        resultMap.put("total", records.size());

        return resultMap;
    }
}

